import 'dart:io';

import 'package:flutter/services.dart';
import 'package:path_provider/path_provider.dart';
import 'package:customer_log_app/global/console.dart';
import 'package:sqflite/sqflite.dart';

class SqliteHelper {
  String dbPath = 'assets/db/res.db';
  late Database db;

  open() async {
    try {
      var b = Platform.isAndroid ||
          Platform.isFuchsia ||
          Platform.isIOS ||
          Platform.isLinux ||
          Platform.isMacOS ||
          Platform.isWindows;

      if (b) {
        // log('databasesPath:$databasesPath');

        // log('dbPath:$dbPath');

        Directory appDir = await getApplicationDocumentsDirectory();

        String newDbPath = "${appDir.path}\\$dbPath";

        // log('newDbPath:$newDbPath');

        var f = File(newDbPath);
        var b = await f.exists();
        // var exists = await databaseFactory.databaseExists(dbPath);
        if (!b) {
          // Should happen only the first time you launch your application
          log("Creating new copy from asset");
          log(newDbPath);
          ByteData data = await rootBundle.load(dbPath);
          List<int> bytes =
              data.buffer.asUint8List(data.offsetInBytes, data.lengthInBytes);
          // Write and flush the bytes written
          try {
            await File(newDbPath).create(recursive: true);
          } catch (_) {}
          await File(newDbPath).writeAsBytes(bytes, flush: true);
          log('file write:$newDbPath');
        } else {
          // log("Opening existing database");
        }

        var db = await databaseFactory.openDatabase(newDbPath);

        return db;
      } else {
        log('not supported');
      }
    } catch (e) {
      log('sqlite error');
      log(e);
    }
  }

  Future<List<Map>> getData(String sql) async {
    log(sql);
    var db = await open();
    var result = await db.rawQuery(sql);
    // log(result);
    return result;
  }

  delete(String sql) async {
    log('delete data');
    var db = await open();
    await db.rawDelete(sql);
  }

  updateData(String sql) async {
    log('update data');
    log(sql);
    var db = await open();
    // int id = 0;
    await db.rawUpdate(sql);
  }

  insertData(String tableName, Map<String, Object?> value) async {
    log('insert data');
    var db = await open();
    // int id = 0;
    int id = await db.insert(tableName, value);
    return id;
  }

  void check() async {
    log('sync datatable ');
    var db = await open();
    String sql;

    try {
      sql =
          'CREATE TABLE "translation" ("id"  INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,"key"  TEXT,"ug"  TEXT,"cn"  TEXT,"en"  TEXT);';
      db.execute(sql);
    } on Exception catch (_) {}
    //create table me
    try {
      sql = 'CREATE TABLE "me" ("id" ';
      sql += ' INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,';
      sql += '"number"  TEXT,"pass"  TEXT,"name"  TEXT,"name_cn"  TEXT,';
      sql += ' "phone"  TEXT,"image"  TEXT,"address"  TEXT,"in_date"  TEXT,';
      sql += ' "birth_day"  TEXT,"marriy_date"  TEXT,';
      sql += ' "info"  TEXT,"interest"  TEXT);';

      db.execute(sql);
    } on Exception catch (_) {}

    //create table translation
    try {
      sql =
          'CREATE TABLE "translation" ("id"  INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,"key"  TEXT,"ug"  TEXT,"cn"  TEXT,"en"  TEXT);';
      db.execute(sql);
    } on Exception catch (_) {}
  }
}
